<template>
  <div class="page-marketing-coupon">
    <div class="coupon-mod">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form
          ref="test-form"
          :inline="true"
          class="search-form"
          :model="searchForm"
          @submit.prevent
        >
          <div class="input-row">
            <el-form-item
              :label="$t('coupon.shopName') + ':'"
              class="search-form-item"
            >
              <el-input
                v-model="searchForm.shopName"
                clearable
                :placeholder="$t('coupon.shopName')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('coupon.couponName') + ':'"
              class="search-form-item"
            >
              <el-input
                v-model="searchForm.couponName"
                clearable
                :placeholder="$t('coupon.couponName')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('coupon.expiredStatus') + ':'"
              class="search-form-item"
            >
              <el-select
                v-model="searchForm.overdueStatus"
                clearable
                :placeholder="$t('coupon.expiredStatus')"
              >
                <el-option
                  v-for="item in searchForm.overdueStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('coupon.deliveryStatus') + ':'"
              class="search-form-item"
            >
              <el-select
                v-model="searchForm.putonStatus"
                :placeholder="$t('coupon.deliveryStatus')"
                clearable
              >
                <el-option
                  v-for="item in searchForm.putonStatuList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- 日期组件 -->
            <el-form-item :label="$t('coupon.expire') + ':'">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                clearable
                :range-separator="$t('date.tip')"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                                new Date(2000, 2, 1, 23, 59, 59)]"
                :start-placeholder="$t('date.start')"
                :end-placeholder="$t('date.end')"
              />
            </el-form-item>
            <el-form-item>
              <div
                class="default-btn primary-btn"
                @click="onSearch(true)"
              >
                {{ $t('shopFeature.searchBar.search') }}
              </div>
              <div
                class="default-btn"
                @click="clearSearch"
              >
                {{ $t('product.reset') }}
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 搜索栏end -->
      <!-- 表格主体 -->
      <div class="main-container">
        <!-- 表格 -->
        <div class="table-con seckill-table">
          <el-table
            :data="dataList"
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
            style="width: 100%"
          >
            <el-table-column
              fixed
              prop="shopName"
              :label="$t('coupon.shopName')"
              min-width="120"
            >
              <template #default="scope">
                <div>
                  <span class="table-cell-text">{{ scope.row.shopName || '-' }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column
              fixed
              prop="couponName"
              :label="$t('coupon.couponName')"
              min-width="200"
            >
              <template #default="scope">
                <div>
                  <span class="table-cell-text">{{ scope.row.couponName || '-' }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column
              prop="couponType"
              :label="$t('coupon.couponType')"
              min-width="120"
            >
              <template #default="scope">
                <div class="tag-text">
                  {{ ['',$t("coupon.cashCoupon"), $t("coupon.discountVoucher"),
                      $t("coupon.coinCertificate")]
                    [scope.row.couponType] }}
                </div>
              </template>
            </el-table-column>

            <el-table-column
              prop="startTime"
              :label="$t('coupon.startTime')"
              min-width="160"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.startTime || '-' }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="endTime"
              :label="$t('coupon.endTime')"
              min-width="160"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.endTime || '-' }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="overdueStatus"
              :label="$t('coupon.expiredStatus')"
              min-width="120"
            >
              <template #default="scope">
                <div class="tag-text">
                  {{ [$t("coupon.expired"), $t("coupon.notExpired")]
                    [scope.row.overdueStatus] }}
                </div>
              </template>
            </el-table-column>

            <el-table-column
              prop="putonStatus"
              :label="$t('coupon.deliveryStatus')"
              min-width="120"
            >
              <template #default="scope">
                <div
                  v-if="scope.row.putonStatus!==-1"
                  class="tag-text"
                >
                  {{ [$t("coupon.waitAutoLaunch"), $t("coupon.launched"), $t("coupon.violationOffShelf"), $t("coupon.waitingForReview"), $t("coupon.waitLaunch")]
                    [scope.row.putonStatus] }}
                </div>
                <div
                  v-else
                  class="tag-text"
                >
                  {{ $t("coupon.cancelLaunch") }}
                </div>
              </template>
            </el-table-column>

            <el-table-column
              prop="launchTime"
              :label="$t('coupon.timeToMarket')"
              min-width="160"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.launchTime || '-' }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="stocks"
              :label="$t('coupon.stock')"
              sortable
              min-width="100"
              align="center"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.stocks || '0' }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="takeNum"
              :label="$t('dataAnalysis.receiveTimes')"
              sortable
              min-width="110"
              align="center"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.takeNum || '0' }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="useNum"
              :label="$t('dataAnalysis.miniMallUsedTimes')"
              sortable
              min-width="160"
              align="center"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.useNum || '-' }}</span>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              :label="$t('crud.menu')"
              min-width="230"
            >
              <template #default="scope">
                <div class="text-btn-con">
                  <div
                    class="default-btn text-btn"
                    @click="onAddOrUpdate(scope.row.couponId)"
                  >
                    {{ $t("seckill.view") }}
                  </div>
                  <div
                    v-if="isAuth('platform:coupon:update') && (scope.row.putonStatus<2 || scope.row.putonStatus === 4) && scope.row.overdueStatus === 1"
                    class="default-btn text-btn"
                    @click="offlineCouponHandle(scope.row)"
                  >
                    {{ $t("product.violation") }}
                  </div>
                  <div
                    v-if="isAuth('platform:coupon:update') && scope.row.putonStatus > 1 && scope.row.putonStatus < 4"
                    class="default-btn text-btn"
                    @click="couponAuditHandle(scope.row.couponId)"
                  >
                    {{
                      scope.row.putonStatus === 2
                        ? $t("prodList.offShelfManage")
                        : $t("coupon.checkPending")
                    }}
                  </div>
                  <div
                    class="default-btn text-btn"
                    @click="onDelete(scope.row.couponId)"
                  >
                    {{ $t("coupon.delete") }}
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <el-pagination
          v-if="dataList.length"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
      <!-- 表格主体end -->
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
    <!-- 商品审核弹窗 -->
    <offline-audit
      v-if="couponAuditVisible"
      ref="couponAuditRef"
      select-url="/platform/coupon/getOfflineHandleEventByCouponId"
      update-url="/platform/coupon/auditCoupon"
      @refresh-data-list="refreshChange"
    />
    <!-- 下线弹窗 -->
    <el-dialog
      v-model:visible="offlineDialogVisible"
      :title="$t('text.tips')"
      append-to-body
      :close-on-click-modal="false"
      destroy-on-close
      class="remarks"
    >
      <el-input
        v-model="offlineReason"
        type="textarea"
        :rows="2"
        maxlength="200"
        :placeholder="$t('coupon.offlineReasonTips')"
      />
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="offlineDialogVisible = false"
          >
            {{ $t('remindPop.cancel') }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="offlineSubmit"
          >
            {{ $t('shopProcess.submit') }}
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { isAuth } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddOrUpdate from './add-or-update.vue'

let tempSearchForm = null // 保存上次点击查询的请求条件
let theParams = null // 保存上次点击查询的请求条件

const dataForm = reactive({
  orderNumber: '',
  status: null
})
const dateRange = ref([])
const dataList = ref([])
const dataListLoading = ref(false)
const addOrUpdateVisible = ref(false)
const couponAuditVisible = ref(false)
const isSubmit = ref(false)
const offlineDialogVisible = ref(false) // 下线提示弹窗
const offlineReason = ref('') // 下线理由
const couponId = ref('') // 当前操作的优惠券id
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
// 头部搜索表单
const searchForm = reactive({
  shopName: null,
  couponName: null,
  overdueStatus: null,
  putonStatus: null,
  getWay: null,
  overdueStatusList: [
    {
      value: 1,
      label: $t('coupon.notExpired')
    }, {
      value: 0,
      label: $t('coupon.expired')
    }
  ],
  putonStatuList: [
    {
      value: -1,
      label: $t('coupon.cancelLaunch')
    },
    {
      value: 0,
      label: $t('coupon.waitAutoLaunch')
    },
    {
      value: 1,
      label: $t('coupon.launched')
    },
    {
      value: 2,
      label: $t('coupon.violationOffShelf')
    },
    {
      value: 3,
      label: $t('coupon.waitingForReview')
    },
    {
      value: 4,
      label: $t('coupon.waitLaunch')
    }]
})

onMounted(() => {
  getDataList()
})

/**
 * 获取数据列表
 * @param pageParam
 * @param newData
 */
const getDataList = (pageParam, newData = false) => {
  dataListLoading.value = true
  if (newData || !tempSearchForm) {
    theParams = JSON.parse(JSON.stringify(searchForm))
    tempSearchForm = {
      current: pageParam == null ? page.currentPage : pageParam.currentPage,
      size: pageParam == null ? page.pageSize : pageParam.pageSize,
      couponName: dataForm.couponName,
      overdueStatus: dataForm.overdueStatus,
      putonStatus: dataForm.putonStatus,
      startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
      endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
    }
  } else {
    tempSearchForm.current = pageParam == null ? page.currentPage : pageParam.currentPage
    tempSearchForm.size = pageParam == null ? page.pageSize : pageParam.pageSize
  }
  http({
    url: http.adornUrl('/platform/coupon/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(tempSearchForm, theParams), false
    )
  })
    .then(({ data }) => {
      dataList.value = data.records
      page.total = data.total
      dataListLoading.value = false

      // 末尾页数据为空重新请求
      if (!dataList.value.length && page.currentPage > 1) {
        page.currentPage = 1
        getDataList()
      }
    })
}

const addOrUpdateRef = ref(null)
/**
 * 新增 / 修改
 * @param val
 */
const onAddOrUpdate = (val) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(val)
  })
}

/**
 * 删除
 * @param id
 */
const onDelete = (id) => {
  ElMessageBox.confirm($t('coupon.Tips2') + `${id ? $t('coupon.delete') : $t('coupon.batchDelete')}` + $t('coupon.Tips3'), $t('coupon.TipsTitle'), {
    confirmButtonText: $t('coupon.confirm'),
    cancelButtonText: $t('coupon.cancel'),
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl('/platform/coupon'),
        method: 'delete',
        data: http.adornData(id, false)
      })
        .then(() => {
          ElMessage({
            message: $t('publics.operation'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              refreshChange()
            }
          })
        })
    })
}

/**
 * 条件查询
 * @param newData
 */
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

/**
 * 刷新回调用
 */
const refreshChange = () => {
  getDataList(page)
}

/**
 * 下线活动
 * @param row
 */
const offlineCouponHandle = (row) => {
  ElMessageBox.prompt($t('coupon.Tips0') + row.couponName + $t('coupon.Tips1'), $t('coupon.TipsTitle'), {
    confirmButtonText: $t('coupon.confirm'),
    cancelButtonText: $t('coupon.cancel'),
    inputPattern: /\s\S+|S+\s|\S/, // 不能全为空格 空字符串
    inputErrorMessage: $t('coupon.offlineReasonNotEmpty'),
    inputValidator: (value) => {
      if (value.length > 100) {
        return $t('seckill.offlineReasonTip1')
      }
    }
  })
    .then((obj) => {
      http({
        url: http.adornUrl('/platform/coupon/offline'),
        method: 'post',
        data: http.adornData({
          handleId: row.couponId,
          offlineReason: obj.value || null
        })
      })
        .then(() => {
          ElMessage({
            message: $t('publics.operation'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              getDataList(page)
            }
          })
        })
    })
}

/**
 * 提交下线操作
 */
const offlineSubmit = () => {
  if (isSubmit.value) {
    return
  }
  isSubmit.value = true
  if (!offlineReason.value.trim() || offlineReason.value.trim().length > 200) {
    ElMessage({
      message: $t('coupon.offlineReasonNotEmpty'),
      type: 'error',
      duration: 1000
    })
    isSubmit.value = false
    return
  }

  http({
    url: http.adornUrl('/platform/coupon/offline'),
    method: 'post',
    data: http.adornData({
      handleId: couponId.value,
      offlineReason: offlineReason.value
    })
  })
    .then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          offlineDialogVisible.value = false
          isSubmit.value = false
          getDataList(page)
        }
      })
    })
    .catch(() => {
      isSubmit.value = false
    })
}

const couponAuditRef = ref(null)
/**
 * 弹窗处理
 * @param id
 */
const couponAuditHandle = (id) => {
  couponAuditVisible.value = true
  nextTick(() => {
    couponAuditRef.value?.init(id)
  })
}

const clearSearch = () => {
  dateRange.value = []
  searchForm.shopName = null
  searchForm.couponName = null
  searchForm.overdueStatus = null
  searchForm.putonStatus = null
}

/**
 * 每页数量变更
 * @param val
 */
const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}

/**
 * 页数变更
 * @param val
 */
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}
</script>

<style lang="scss" scoped>
.page-marketing-coupon {
  .prod-tit span {
    margin-right: 15px;
  }
  .prod-cont .item span {
    display: block;
  }
  .prod-price span {
    display: block;
    margin-bottom: 10px;
  }
  .item span {
    display: block;
    margin-bottom: 10px;
  }
}

</style>
